package com.yanftch.json2ets

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.ui.DialogWrapper
import com.yanftch.json2ets.json2ets.FilePostfix
import com.yanftch.json2ets.json2ets.generator.GeneratorDelegateJava
import com.yanftch.json2ets.json2ets.generator.MessageDelegate
import com.yanftch.json2ets.json2ets.parser.typescript.ParseType
import com.yanftch.json2ets.json2ets.views.Json2TsDialog
import com.yanftch.json2ets.json2ets.views.SetGetChooseDialog

class Json2etsAction : AnAction() {

    private val generatorDelegate = GeneratorDelegateJava(MessageDelegate())

    override fun actionPerformed(event: AnActionEvent) {
        // 获取文件名字
        var fileName: String? = ""
        if (event.project == null) {
            fileName = null
        } else {
            val name = FileEditorManager.getInstance(event.project!!).selectedEditor?.file?.name ?: ""
            var split : List<String> = ArrayList()
            if (name.endsWith(FilePostfix.ETS)) {
                split = name.split(FilePostfix.ETS)
            } else if (name.endsWith(FilePostfix.TS)) {
                split = name.split(FilePostfix.TS)
            }
            if (split.size == 2) {
                fileName = split[0]
            }
        }

        val dialog = Json2TsDialog(fileName)
        dialog.setOnGenerateListener(object : Json2TsDialog.OnGenerateClicked {
            override fun onClicked(rootName: String, json: String, parseType: ParseType) {
                var generateSetGet = false
                if (ParseType.TSClass == parseType) {
                    val dialog = SetGetChooseDialog()
                    dialog.setOnButtonClickListener { isConfirm ->
                        // 生成 set()/get() 方法
                        generateSetGet = isConfirm
                    }
                    dialog.isVisible = true
                } else {
                    generateSetGet = false
                }
                dialog.close(DialogWrapper.OK_EXIT_CODE)
                generatorDelegate.runGeneration(event, json, rootName, parseType, generateSetGet)
            }
        })
        dialog.show()
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    }

    override fun update(e: AnActionEvent) {
        e.presentation.isEnabled = true
    }
}
